package xmysql

import (
	"fmt"

	"gitee.com/githubdog/goci/tools/helper"
)

func getDsnByConf(conf DBConf, protocol string) string {
	paramStr := helper.MapSortToString(conf.Other)
	if paramStr != "" {
		paramStr = "?" + paramStr
	}
	passwordStr := conf.Password
	if conf.Password != "" {
		passwordStr = ":" + conf.Password
	}

	// [username[:password]@][protocol[(address)]]/dbname[?param1=value1&...&paramN=valueN]
	return fmt.Sprintf("%s%s@%s(%s)/%s%s", conf.Username, passwordStr, protocol, conf.Host, conf.DBname, paramStr)
}

// ConnMysql 连接mysql
func (dbs *DbGroup) ConnMysql() (DbTCP, error) {
	var (
		err error
		ret DbTCP
	)

	if dbs.ConnType == "ssh" {
		if dbs.SSH.DbClient != nil && dbs.SSH.checkConn(dbs.TCP.Conf, dbs.SSH.SSHConf) {
			// fmt.Print("SSH 旧连接")
			if e := dbs.SSH.DbQueryTest(); e == nil {
				// fmt.Println(" ok")
				return dbs.SSH.DbTCP, nil
			}
		}
		if err = dbs.SSH.Conn(dbs.TCP.Conf, dbs.SSH.SSHConf); err == nil {
			// fmt.Println("SSH 新连接")
			if err = dbs.SSH.DbQueryTest(); err == nil {
				ret = dbs.SSH.DbTCP
			}
		}
	} else {
		if dbs.TCP.DbClient != nil && dbs.TCP.checkConn(dbs.TCP.Conf) {
			// fmt.Print("TCP 旧连接")
			if e := dbs.TCP.DbQueryTest(); e == nil {
				// fmt.Println(" ok")
				return dbs.TCP, nil
			}
		}
		if err = dbs.TCP.Conn(dbs.TCP.Conf); err == nil {
			// fmt.Println("TCP 新连接")
			if err = dbs.TCP.DbQueryTest(); err == nil {
				ret = dbs.TCP
			}
		}
	}

	return ret, err
}
